package com.tang.framework.config.mybatisPlus.handler;

import com.tang.common.constant.Constant;
import org.apache.ibatis.type.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @Author tang jun liang
 * @Date 2023/10/19 11:44
 */
@MappedTypes({BigDecimal.class})
public class BigDecimalTypeHandler extends BaseTypeHandler<BigDecimal> {
    @Override
    public void setParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
        ps.setBigDecimal(i, parameter.setScale(2, RoundingMode.UP).multiply(Constant.HUNDRED));
    }

    @Override
    public BigDecimal getResult(ResultSet rs, String columnName) throws SQLException {
        BigDecimal bigDecimal = rs.getBigDecimal(columnName);
        if (Objects.nonNull(bigDecimal)){
            return bigDecimal.divide(Constant.HUNDRED, 2, RoundingMode.UP);
        }
        return BigDecimal.ZERO;

    }

    @Override
    public BigDecimal getResult(ResultSet rs, int columnIndex) throws SQLException {
        BigDecimal bigDecimal = rs.getBigDecimal(columnIndex);
        if (Objects.nonNull(bigDecimal)){
            return bigDecimal.divide(Constant.HUNDRED, 2, RoundingMode.UP);
        }
        return BigDecimal.ZERO;

    }

    @Override
    public BigDecimal getResult(CallableStatement cs, int columnIndex) throws SQLException {
        BigDecimal bigDecimal = cs.getBigDecimal(columnIndex);
        if (Objects.nonNull(bigDecimal)){
            return bigDecimal.divide(Constant.HUNDRED, 2, RoundingMode.UP);
        }
        return BigDecimal.ZERO;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BigDecimal parameter, JdbcType jdbcType) throws SQLException {
        setParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return BigDecimal.ZERO;
    }

    @Override
    public BigDecimal getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return BigDecimal.ZERO;
    }

    @Override
    public BigDecimal getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return BigDecimal.ZERO;
    }

}
